package nl.infodation.emr.pricingservice.data;

import java.io.IOException;
import java.util.Map;

import nl.infodation.emr.utility.ConfigurationReader;
import nl.infodation.emr.utility.Constants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gwt.dev.util.collect.HashMap;

public final class ResourceRepository {

	private static final Logger LOG = LoggerFactory.getLogger(ResourceRepository.class);
	private static Map<String, String> sqlContents = new HashMap<String, String>();
	private static Map<String, String> props = new HashMap<String, String>();
	
	/**
	 * Make singleton, since all methods are static.
	 */
	private ResourceRepository() {
		// no-op
	}
	
	/**
	 * 
	 * @param key Name of the value in name=value pair.
	 * @return corresponding value from the file PORTFOLIO_PROPERTY_FILE. Or null when name is not present
	 * @see #getProperties()
	 * @see Constants#PORTFOLIO_PROPERTY_FILE
	 */
	public static String getPropety(final String key) {
		String result = null;
		if (key != null) {
			result =  getProperties().get(key);
		}
		return result;
	}
	
	/**
	 * This method lazily initializes SQL properties. 
	 * When those properties could not be read this method returns an empty Map. 
	 * @return mapping of query names to Hibernate queries, never null.
	 */
	public static Map<String, String> getCommonSQL() {
		synchronized (sqlContents) {
			if (sqlContents.isEmpty()) {
				try {
					sqlContents = ConfigurationReader.getPropertyUtil()
							.loadCommonSQLProperties();
				} catch (IOException ioException) {
					LOG.error("Unable to load SQL Properties.", ioException);
				}
			}
		}
		return sqlContents;
	}
	
	/**
	 * This method lazily initializes Portfolio properties. 
	 * When those properties could not be read this method returns an empty Map. 
	 * @return mapping of property names to String values, never null.
	 */
	public static Map<String, String> getProperties(){
		synchronized (props) {
			if (props.isEmpty()){
				try{
					props = ConfigurationReader.getPropertyUtil().loadPricingProperties();
				} catch (IOException ioException) {
					LOG.error("Error loading portfolio properties.", ioException);
				}
			}
		}
		return props;
	}
}
